package org.hit.burkun.index.term;

import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;
import org.hit.burkun.extract.FiledsToEntityMapper;
import org.hit.burkun.extract.FiledsToEntityMapper.FILED;
import org.hit.burkun.umls.GeneralQuery;

public class ExtractGeneralTerm {

	private FiledsToEntityMapper mapper;
	private DBHelper termDbh;
	private DBHelper umlsDbh;
	private GeneralQuery jquery;

	public ExtractGeneralTerm(FiledsToEntityMapper mapper, DBHelper termDbh,
			DBHelper umlsDbh) {
		this.mapper = mapper;
		this.termDbh = termDbh.clone();
		this.umlsDbh = umlsDbh.clone();
		// 设定未map上的不自动更新
		this.jquery = new GeneralQuery(this.umlsDbh, "map_umls_ids", false);
	}

	private Collection<String[]> getAllTerms() {
		String queryStr = mapper.buildQueryAllData();
		termDbh.connectionDB();
		Collection<String[]> res = termDbh.queryData(queryStr,
				mapper.getFiledsSize());
		termDbh.disconnection();
		return res;
	}

	// 真的元组
	private Collection<IndexTerm> getIndexTerms(Collection<String[]> res) {
		Collection<String> dbids = new LinkedList<>();
		Collection<IndexTerm> indexTerms = new LinkedList<>();
		for (String[] line : res) {
			int iname = mapper.getResultIdxByFiled(FILED.NAME);
			int idef = mapper.getResultIdxByFiled(FILED.DEF);
			int idbid = mapper.getResultIdxByFiled(FILED.DBID);
			int ipid = mapper.getResultIdxByFiled(FILED.PRIMARY_ID);
			String name = iname == -1 ? null : line[iname];
			String def = idef == -1 ? null : line[idef];
			String dbid = line[idbid];
			String pid = ipid == -1 ? null : line[ipid];
			String url = formatUrl(mapper.getType(), dbid);
			dbids.add(dbid);
			Entity entity = new Entity(pid, name, null, dbid, mapper.getType());
			entity.setDef(def);

			IndexTerm iterm = new IndexTerm(url, mapper.getTbName(), entity);
			indexTerms.add(iterm);
		}
		// 获取全局uid
		jquery.begin();
		jquery.quickMap(dbids, mapper.getType());
		Map<String, Set<String>> map = jquery.getResult();
		jquery.end();
		for (IndexTerm term : indexTerms) {
			String dbid = term.getEntity().getDbid();
			if (map.containsKey(dbid)) {
				String cuis = StringUtils.join(map.get(dbid), ",");
				term.getEntity().setUid(cuis);
			}
		}
		return indexTerms;
	}

	// 组装成真正的url
	private String formatUrl(Entity.TYPE type, String dbid) {
		String urlPattern = DBCollection.getEntityUrl(type);
		return urlPattern.replaceAll("\\[example_id\\]", dbid);
	}

	public Collection<IndexTerm> getTermSet() {
		if (!mapper.isFake()) {
			// 不是假的
			Collection<String[]> res = getAllTerms();
			Collection<IndexTerm> terms = getIndexTerms(res);
			return terms;
		}
		return null;
	}

	public static void main(String[] args) {

	}

}